// pages/goods_detail/index.js
import {request} from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: '',
    // 商品最开始未被收藏
    isCollect: false
  },
  
  goodsInfo: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let pages =  getCurrentPages();
    let currentPage = pages[pages.length-1]
    let options = currentPage.options
    const goods_id = options.goods_id
    this.getGoodsList(goods_id)
  },
  // 商品收藏按钮点击事件
  handleCollect: function () {
    // 1. 判断该商品是否在本地存储的收藏数组中
    let isCollect = false 
    let collect = wx.getStorageSync("collect") || []
    let index = collect.findIndex(v => v.goods_id == this.goodsInfo.goods_id)
    if(index == -1) {
      // 商品不在收藏里
      isCollect = true
      collect.push(this.goodsInfo)
      wx.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 1500,
        mask: true
      })
        
    } else {
      // 商品在收藏里，把它删掉
      isCollect = false 
      collect.splice(index, 1)
      wx.showToast({
        title: '取消成功',
        icon: 'success',
        duration: 1500,
        mask: true
      });
    }
    this.setData({
      isCollect
    })
    wx.setStorageSync('collect', collect)
  },
  async getGoodsList (goods_id) {
    // 参数格式： data:{参数}
    const data = await request({url: "/goods/detail", data:{goods_id}})
    this.goodsInfo = data.data.message
     // 1. 获取本地的商品收藏数组
     let collect = wx.getStorageSync("collect") || []
    //  2. 判断当前商品是否被收藏
    let isCollect = collect.some(v => {
      this.goodsInfo.goods_id === v.goods_id
    })
    this.setData({
      isCollect,
      goodsList: {
        goods_name: data.data.message.goods_name,
        goods_price: data.data.message.goods_price,
        // 全局替换
        goods_introduce: data.data.message.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: data.data.message.pics
      }
    })
    console.log(this.data.goodsList)

  },
  handlePreviewImage: function (e) {
    // 先构造要预览的图片数据
    const url = this.goodsInfo.pics.map(v=>v.pics_mid)
    // 传递过来图片的url
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      current,
      urls: url
    });
      
  },
  // 加入购物车
  handleCartAdd: function () {
    let cart = wx.getStorageSync('cart') || []
    let index = cart.findIndex(v => v.goods_id == this.goodsInfo.goods_id)
    if (index == -1) {
      // 不存在，就是第一次添加
      this.goodsInfo.num = 1
      this.goodsInfo.checked = true
      cart.push(this.goodsInfo)
    } else {
      // 已经存在，num++
      cart[index].num++
    }
    // 把数据重新添加到缓存中
    wx.setStorageSync("cart", cart);
    // 弹窗显示
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      image: '',
      duration: 1500,
      // 防止用户手抖，一直点击按钮
      mask: true
    });
  }
})